package com.wehealth.electrocardiograph_two_client.activity;

 import static com.wehealth.electrocardiograph_two_client.constant.EcgConstant.Version_ECG;
  import static com.wehealth.three.lib_connect.constant.ConstantKey.PATIENT_USER_AGE;
 import static com.wehealth.three.lib_connect.constant.ConstantKey.PATIENT_USER_GENDER;
 import static com.wehealth.three.lib_connect.constant.ConstantKey.PATIENT_USER_ID;
 import static com.wehealth.three.lib_connect.constant.ConstantKey.PATIENT_USER_NAME;
 import static com.wehealth.three.lib_connect.constant.ConstantKey.USER_ECG_FILE_SAVE_TYPE;
 import static com.wehealth.three.lib_connect.constant.ConstantKey.USER_ECG_SEARCH_TYPE;
 import static com.wehealth.three.lib_connect.constant.ConstantKey.USER_WAVE_PACE;

 import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.MediaController;

 import com.wehealth.electrocardiograph_two_client.constant.EcgConstant;
import com.wehealth.electrocardiograph_two_client.R;
import com.wehealth.three.lib_common.utils.DensityUtil;
import com.wehealth.three.lib_common.utils.ResUtlis;
import com.wehealth.three.lib_common.utils.StatusBarUtil;
import com.wehealth.three.lib_common.widget.DiyVideoView;
 import com.wehealth.three.lib_connect.constant.ConstantKey;
 import com.wehealth.biz_ecg.ui.ECGMeasureActivity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class EcgGuideVideoActivity extends Activity implements MediaPlayer.OnErrorListener, MediaPlayer.OnCompletionListener {
    //用户的信息
    private String patientId = "";
    private String patientName = "";
    private int patientAge = 0;
    private int patientGender = 0;

    //当前参数控制绘制的心电图的增益 增益是有一个默认的数值 在测量的页面是可以修改的
    private int waveGain = 4;
    // 控制的是当前的纸速  纸速也是有一个默认的数值 ，在测量的页面可以修改
    private int waveSpeed = 0;
    //绘制的心电图的样式   显示模式也是又要给默认的样式 在测量的页面可以修改  是否需要上层应用传递？
    //设置为0, 6ch*2 模式; 为1, 12ch*1模式；   为2， 1ch*1模式
    private int waveDisplayType = 0;
    //控制的是绘制12导的具体哪一个导联
    private int waveSingleDisplaySwitch = 0;
    public int searchType = 0;

    //2为24小时；1为人工Manual；0为自动 Auto:10秒数据  当前的测量类型 需要上层应用传递参数过来
    private int saveFileType = 1;

    //是否开启起搏 也需要上层应用配置
    private boolean waveIsPace = false;

    private Uri mUri;
    private ProgressDialog upLoadEcgDialog;
    private DiyVideoView videoView;
    private float scale;
    private int mVideoWidth, mVideoHeight, showVideoHeight;


    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 101:
                    onNextStep();
                    break;
                case 102:
                    if (upLoadEcgDialog != null && upLoadEcgDialog.isShowing()) {
                        upLoadEcgDialog.dismiss();
                    }
                    //Video file
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                        mUri = Uri.parse(EcgGuideVideoActivity.this.getExternalFilesDir(Version_ECG) + "/device2clinic.mp4");
                    } else {
                        mUri = Uri.parse(EcgConstant.INSTANCE.PATH_ECG_DATA_PDF + "/device2clinic.mp4");
                    }

                    //Create media controller
                    videoView.setVideoURI(mUri);
                    startVideoMeasureView();
                    break;
                case 103:
                    upLoadEcgDialog.show();
                    break;

                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_guide_video);
        StatusBarUtil.INSTANCE.setStatusBar(EcgGuideVideoActivity.this, false, ResUtlis.INSTANCE.getColor(R.color.title_back_color), false);
        upLoadEcgDialog = new ProgressDialog(this);
        upLoadEcgDialog.setCancelable(false);
        upLoadEcgDialog.setCanceledOnTouchOutside(false);
        upLoadEcgDialog.setMessage(getResources().getString(R.string.guide_video_loading));

        videoView = findViewById(R.id.video_view);
        videoView.post(() -> showVideoHeight = videoView.getMeasuredHeight());

        MediaController mMediaController = new MediaController(this);
        videoView.setMediaController(mMediaController);
        videoView.setOnCompletionListener(this);

        Intent intent = getIntent();

        if (intent != null) {
            patientId = intent.getStringExtra(PATIENT_USER_ID);
            searchType = intent.getIntExtra(USER_ECG_SEARCH_TYPE, 0);
            patientAge = intent.getIntExtra(PATIENT_USER_AGE, 60);
            patientName = intent.getStringExtra(PATIENT_USER_NAME);
            patientGender = intent.getIntExtra(PATIENT_USER_GENDER, 0);
            waveGain = intent.getIntExtra(ConstantKey.USER_WAVE_GAIN, 4);
            waveSpeed = intent.getIntExtra(ConstantKey.USER_WAVE_SPEED, 0);
            waveDisplayType = intent.getIntExtra(ConstantKey.USER_WAVE_DISPLAY, 0);
            waveIsPace = intent.getBooleanExtra(USER_WAVE_PACE, false);
            saveFileType = intent.getIntExtra(USER_ECG_FILE_SAVE_TYPE, 0);
        }

        File mp4File;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            mp4File = new File(getExternalFilesDir(Version_ECG) + "/device2clinic.mp4");
        } else {
            mp4File = new File(EcgConstant.INSTANCE.PATH_ECG_DATA_PDF + "/device2clinic.mp4");
        }
        if (!mp4File.exists()) {
            Log.e("TAG", "mp4 不存在");
            handler.sendEmptyMessage(103);
            read2WriteSD();
        } else {
            //Video file
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                mUri = Uri.parse(getExternalFilesDir(Version_ECG) + "/device2clinic.mp4");
            } else {
                mUri = Uri.parse(EcgConstant.INSTANCE.PATH_ECG_DATA_PDF + "/device2clinic.mp4");
            }
            Log.e("TAG", "开始Uri");

            //Create media controller
            videoView.setVideoURI(mUri);

            startVideoMeasureView();
        }
    }

    private void startVideoMeasureView() {
        videoView.setOnPreparedListener(mp -> mp.setOnVideoSizeChangedListener((mp1, width, height) -> {
            //FixMe 获取视频资源的宽度
            mVideoWidth = mp1.getVideoWidth();
            //FixMe 获取视频资源的高度
            mVideoHeight = mp1.getVideoHeight();
            scale = (float) mVideoWidth / (float) mVideoHeight;
            refreshPortraitScreen(showVideoHeight == 0 ? DensityUtil.dip2px(EcgGuideVideoActivity.this, 300) : showVideoHeight);
        }));
        videoView.start();
    }

    //重新刷新 竖屏显示的大小  树屏显示以宽度为准
    public void refreshPortraitScreen(int height) {
        if (height == 0) {
            height = showVideoHeight;
        }
        if (mVideoHeight > 0 && mVideoWidth > 0) {
            //FixMe 拉伸比例

            mVideoWidth = (int) (height * scale);//FixMe 设置surfaceview画布大小
//            mVideoHeight = (int) (mVideoWidth / scale);
            videoView.getHolder().setFixedSize(mVideoWidth, height);
//            Log.e("TAG","竖屏时视频的宽高  ==   "+"宽=" + mVideoWidth + "，高=" + mVideoHeight);
            //FixMe 重绘VideoView大小，这个方法是在重写VideoView时对外抛出方法
            videoView.setMeasure(mVideoWidth, height);
            //FixMe 请求调整
            videoView.requestLayout();
        }
    }


    /**
     * 将assets下的文件复制到手机sd卡上
     **/
    private void read2WriteSD() {
        new Thread(() -> {
            try {
                FileOutputStream fos;
                InputStream is = getAssets().open("device2clinic.mp4");
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    fos = new FileOutputStream(EcgGuideVideoActivity.this.getExternalFilesDir(Version_ECG) + "/device2clinic.mp4");
                } else {
                    File fileDir = new File(EcgConstant.INSTANCE.PATH_ECG_DATA_PDF);
                    if (!fileDir.exists()) {
                        fileDir.mkdir();
                    }
                    fos = new FileOutputStream(EcgConstant.INSTANCE.PATH_ECG_DATA_PDF + "/device2clinic.mp4");
                }
                // 2.定义存储空间
                byte[] buffer = new byte[2048];
                // 3.开始读文件
                int len = -1;
                while ((len = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);// 将Buffer中的数据写到outputStream对象中
                }
                fos.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
                handler.sendEmptyMessage(101);
                return;
            }
            handler.sendEmptyMessage(102);
        }).start();
    }

    @Override
    protected void onPause() {
        super.onPause();
        upLoadEcgDialog.dismiss();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public void skipAnim(View view) {
        onNextStep();
    }

    public void onNextStep() {
        Intent intent = new Intent(this, ECGMeasureActivity.class);
        intent.putExtra(PATIENT_USER_ID, patientId);
        intent.putExtra(PATIENT_USER_AGE, patientAge);
        intent.putExtra(PATIENT_USER_GENDER, patientGender);
        intent.putExtra(PATIENT_USER_NAME, patientName);
        intent.putExtra(USER_WAVE_PACE, waveIsPace);
        intent.putExtra(USER_ECG_SEARCH_TYPE, searchType);
         intent.putExtra(USER_ECG_FILE_SAVE_TYPE, saveFileType);
        startActivity(intent);
        finish();
    }

    public void onBackBottonClick(View view) {
        finish();
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        onNextStep();
    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        this.finish();
        return false;
    }

}
